/**设备详情 */
import { useEffect, useState } from 'react';
import { DatePicker, Button, Space, AutoComplete, Input, message } from 'antd';
import dayjs from 'dayjs';

import RecordTable from './RecordTable';
import Icon from '@/components/SvgIcon';

import { useRequest } from 'ahooks';
import { getWorkRecordsAPI, exportWorkRecordAPI } from '@/api/analysis';
import { queryDeviceByCode } from '@/api/device';

import { downloadExcel } from '@/utils';
import { isNull } from '@/utils/is';

import type { Dayjs } from 'dayjs';

import './index.scss';

const { RangePicker } = DatePicker;

type RangeValue = [Dayjs | null, Dayjs | null] | null;
const dateFormat = 'YYYY/MM/DD';
const defaultDate: RangeValue = [
  dayjs(dayjs().add(-31, 'd'), dateFormat),
  dayjs(dayjs().add(-1, 'd'), dateFormat),
];

const DeviceDetail: React.FC<{ code?: string }> = ({ code }) => {
  const [utilizationData, setUtilizationData] = useState<any>();
  const [deviceCode, setDeviceCode] = useState<string | undefined>(code);
  const [keyword, setKeyword] = useState<string>();
  const [deviceOptions, setDeviceOptions] = useState<any[]>([]);
  const [deviceInfo, setDeviceInfo] = useState<any>();

  // 真实date
  const [dateRange, setDateRange] = useState<RangeValue>(defaultDate);
  // 展示date
  const [showDates, setShowDates] = useState<RangeValue>(null);
  const [formData, setFormData] = useState<API.WorkRecord>({
    deviceCode: code ? code : deviceCode,
    startTime: dayjs(defaultDate[0]).format(dateFormat),
    endTime: dayjs(defaultDate[1]).format(dateFormat),
    page: 1,
    pageSize: 20,
  });

  useEffect(() => {
    let startTime = undefined;
    let endTime = undefined;
    if (!isNull(dateRange)) {
      startTime = dayjs(dateRange[0]).format(dateFormat);
      endTime = dayjs(dateRange[1]).format(dateFormat);
    }
    setFormData({
      ...formData,
      startTime,
      endTime,
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dateRange]);

  const exportWorkInfo = () => {
    if (!deviceCode) {
      return message.error('请输入设备编号');
    }
    exportWorkRecord();
  };

  const exportWorkRecord = () => {
    exportWorkRecordAPI({
      ...formData,
      deviceCode,
    }).then(res => {
      downloadExcel(
        res.data,
        decodeURI(
          res.headers['content-disposition'].split('=')[1].split(';')[0]
        )
      );
    });
  };

  // 辅助查询设备编号
  useRequest(() => queryDeviceByCode({ searchKey: keyword }), {
    debounceWait: 500,
    refreshDeps: [keyword],
    onSuccess: res => {
      const options = res.data.map((r: any) => ({
        ...r,
        label: r.deviceCode,
        value: r.deviceCode,
      }));
      setDeviceOptions(options);
      if (code) {
        setDeviceCode(code);
        const info = options.find(dev => dev.deviceCode === code);
        if (info) {
          setDeviceInfo(info);
        }
      }
    },
  });
  // 查询利用率详情
  const { run: searchDeatail, loading } = useRequest(
    () => getWorkRecordsAPI({ ...formData, deviceCode }),
    {
      manual: true,
      onSuccess: res => {
        setUtilizationData(res.data);
      },
    }
  );

  //分页器
  const pageChange = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    setFormData({
      ...formData,
      page,
    });
  };

  const autoSetDeviceCode = (val: string) => {
    setDeviceCode(val);
    const info = deviceOptions.find(dev => dev.deviceCode === val);
    console.log(info, deviceOptions, val);
    if (info) {
      setDeviceInfo(info);
    }
  };

  useEffect(() => {
    if (deviceCode) searchDeatail();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formData.page]);

  return (
    <div className="device-detail flex-column">
      <div className="work-record flex-column flex-auto">
        <div className="operate-wrap">
          <Space>
            <AutoComplete
              defaultValue={deviceCode}
              children={
                <Input
                  prefix={
                    <Icon style={{ color: '#B1B5BD' }} name="icon-search" />
                  }
                  placeholder="请输入设备编号"
                  onChange={e => {
                    if (!e.target.value) setDeviceCode(undefined);
                    setKeyword(e.target.value);
                  }}
                />
              }
              style={{ width: 300 }}
              options={deviceOptions}
              onSelect={val => autoSetDeviceCode(val)}
            />
            <RangePicker
              format={dateFormat}
              value={showDates || dateRange}
              disabledDate={current =>
                current > dayjs().subtract(1, 'day').endOf('day')
              }
              // onOpenChange={openChangeHandle}
              onCalendarChange={val => {
                setShowDates(val);
              }}
              onChange={val => {
                // console.log(val);
                setDateRange(val);
              }}
              changeOnBlur
            />
          </Space>
          <Space className="right">
            <Button
              type="primary"
              onClick={() => {
                searchDeatail();
                setFormData({
                  ...formData,
                  page: 1,
                });
              }}>
              查询
            </Button>
            <Button type="primary" ghost onClick={exportWorkInfo}>
              导出
            </Button>
          </Space>
        </div>
        <div className="flex-column flex-hide">
          <RecordTable
            loading={loading}
            dataSource={utilizationData?.records}
            deviceInfo={deviceInfo}
            pagination={{
              total: utilizationData?.total,
              pageSize: formData.pageSize,
              current: formData.page,
              onChange: pageChange,
              hideOnSinglePage: true,
            }}
          />
        </div>
      </div>
    </div>
  );
};

export default DeviceDetail;
